<?php
class PersonalPageController extends Pidguin_Controller_Public_Action
{
	public function indexAction()
	{
		$this->_redirect('/news');
	}
    
    public function staffWriteAction()
    {
        $select = Model_Groups::getInstance()->select()->from('groups', array('id'))
                ->where('name = "staff"');
        $groupRow = Model_Groups::getInstance()->fetchRow($select);
		if (!$groupRow) {
			throw new Zend_Controller_Action_Exception('Группа с сотрудниками не найдена');
		}
		$userRowset = $groupRow->findDependentRowset('Model_UserGroup');
		if (count($userRowset) <= 0) {
			throw new Zend_Controller_Action_Exception('Извините, нет ни одного сотрудника');
		}
		$usersList = array();
		$usersList[] = 'Выберите сотрудника...';
		foreach ($userRowset as $userRow) {
			$user = $userRow->findParentRow('Model_User', 'User');
			$usersList[$user->id] = $user->name;
		}
		$this->view->user_list = $usersList;
    }
	
	public function messagesAction()
	{
		$user = Pidguin_Client::getInstance()->getClient()->user;
        if ($user->id == 1) {
			throw new Zend_Controller_Action_Exception('Access denied');
		}
        // get user list
        $select = Model_User::getInstance()->select()->from('user', array('login', 'name', 'id'))
                ->where('id != 1')->where('id != ?', $user->id);
        $users = Model_User::getInstance()->fetchAll($select);
        $usersList = array();
        $usersList[0] = 'Выберите пользователя...';
        foreach ($users as $_user) {
            $usersList[$_user->id] = $_user->name . ' ('. $_user->login . ')';
        }
        $this->view->user_list = $usersList;
        $this->view->posted = $user->findDependentRowset('Model_UserMessages', 'Posted', Model_UserMessages::getInstance()->select()->order('created DESC'));
        $this->view->incoming = $user->findDependentRowset('Model_UserMessages', 'Incoming', Model_UserMessages::getInstance()->select()->order('created DESC'));
	}
	
	public function messageReadAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		$user = Pidguin_Client::getInstance()->getClient()->user;
		
		if ($user->id == 1) {
			throw new Zend_Controller_Action_Exception('Access denied');
		}
		
		if (!$this->_getParam('comment_id')) {
			throw new Zend_Controller_Action_Exception('Message ID is not set');
		}
		
		$select = Model_UserMessages::getInstance()->select()->from('user_messages', array('id', 'read'))
				->where('for_user_id = ?', $user->id)->where('id = ?', $this->_getParam('comment_id'));
		$row = Model_UserMessages::getInstance()->fetchRow($select);
		
		if (!$row) {
			throw new Zend_Controller_Action_Exception('Message not found');
		}
		
		$row->read = 1;
		$row->save();
		
		$select = Model_UserMessages::getInstance()->select()->from('user_messages', array('id'))
				->where('`read` = 0')->order('created DESC');
		$this->_helper->json(array(
			'status' => 'ok',
			'new_incoming' => count($user->findDependentRowset('Model_UserMessages', 'Incoming', $select))
		));
	}
	
	public function checkNewIncomingAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		$user = Pidguin_Client::getInstance()->getClient()->user;
		
		if ($user->id == 1) {
			$this->_helper->json(array());
		}
		
		$data = array();
		if ($this->_getParam('href') && $this->_getParam('href') == '/personal.page/messages') {
			$select = Model_UserMessages::getInstance()->select()
				->where('`read` = 0')->order('created DESC');
		} else {
			$select = Model_UserMessages::getInstance()->select()->from('user_messages', array('id', 'created'))
				->where('`read` = 0')->order('created DESC');
		}
		$incoming = $user->findDependentRowset('Model_UserMessages', 'Incoming', $select);
		$data['count_incoming'] = count($incoming);
		
		if ($data['count_incoming'] > 0) {
			if (isset($incoming[0]['message'])) {
				$data['messages'] = array();
				foreach ($incoming as $message) {
					$date = new Zend_Date($message->created, false, Pidguin_Application::getInstance()->getLocale());
					$data['messages'][]= array(
						'id' => $message->id,
						'for_user' => $message->findParentRow('Model_User', 'Incoming')->name,
						'message' => $message->message,
						'created' => $date->toString('d MMMM в HH:mm')
					);
				}
			}
		}
		
		$this->_helper->json($data);
	}
    
    public function messageAddAction()
    {
        if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
        
        if (!$this->_getParam('for_user')) {
			throw new Zend_Controller_Action_Exception('For User is not set');
		}
        
        if (!$this->_getParam('text')) {
			throw new Zend_Controller_Action_Exception('Text is not set');
		}
        
        // find user
        $select = Model_User::getInstance()->select()->from('user', array('id'))
                ->where('id = ?', $this->_getParam('for_user'));
        $userRow = Model_User::getInstance()->fetchRow($select);
        
        if (!$userRow) {
            throw new Zend_Controller_Action_Exception('User not found');
        }
        
        $message = Model_UserMessages::getInstance()->createRow();
        $message->author_id = Pidguin_Client::getInstance()->getClient()->user->id;
        $message->for_user_id = $userRow->id;
        $message->message = strip_tags($this->_getParam('text'), '<a>');
        $message->created = date('Y-m-d H:i:s');
        $message->save();
        $date = new Zend_Date($message->created, false, Pidguin_Application::getInstance()->getLocale());
        $this->_helper->json(array('status' => 'ok', 'message' => array(
            'id' => $message->id,
            'for_user' => $message->findParentRow('Model_User', 'Incoming')->name,
            'message' => $message->message,
            'created' => $date->toString('d MMMM в HH:mm')
        )));
    }
	
	public function indexMinAction()
	{
		$user = Pidguin_Client::getInstance()->getClient()->user;
        
        if ($user->id == 1) {
            $form = new Application_Form_PersonalPage_Auth();
            $this->view->auth = false;
            $this->view->form_auth = $form;
        } else {
            $this->view->user = $user;
            $select = Model_UserMessages::getInstance()->select()->from('user_messages', array('id'))
                    ->where('`read` = 0');
            $this->view->incoming = count($user->findDependentRowset('Model_UserMessages', 'Incoming', $select));
        }
	}
    
    public function loginAction()
    {
        $user = Pidguin_Client::getInstance()->getClient()->user;
        
        if ($user->id != 1) {
            $this->_redirect('/news');
        }
        $form = new Application_Form_PersonalPage_Auth();
		if ($this->getRequest()->isPost()) {
			if ($form->isValid($_POST)) {
				$values = $form->getValues();
				$values['password'] = sha1(md5($values['auth_password'], true));
				// find user				
				$model = Model_User::getInstance();
				$select = $model->select();
				$select->where($model->getAdapter()->quoteInto('login = ?', $values['auth_login']));
				$select->where($model->getAdapter()->quoteInto('password = ?', $values['password']));
				$user = $model->fetchRow($select);
				if (!$user) {
					$this->_helper->json(array(
                        'error' => 'Пользователь не найден',
                        'form' => $form->render()
                    ));
				}
				// авторизовываем
				$client = Pidguin_Client::getInstance();
                $qe = ($this->_getParam('quick_expire') == "false") ? false : true;
				if ($client->authorize($user, false, $qe)){
					$this->_helper->json(array('redirect' => '/news'));
				} else {
					$this->_helper->json(array(
                        'error' => 'Извините, у Вас нет доступа к Персональной странице',
                        'form' => $form->render()
                    ));
				}
			} else {
				$this->_helper->json(array(
                    'form' => $form->render(),
                    'error' => 'Неверно заполнены поля'
                ));
			}
		}
    }
    
    public function logoutAction()
    {
        $this->_disableView();
		
		Pidguin_Client::getInstance()->logout();
		
		$this->_redirect('/');
    }
}